/* model */
import Field from '@model/entity/Field';
import Column from '@model/types/Column';
/* vue */
import { defineComponent, PropType } from 'vue';
/* enum */
import ComponentNameEnum from '@model/enum/ComponentNameEnum';
import { FieldTypeMappingEnum } from '@model/enum/FieldMappingEnum';
/* util */
import { isFalsy } from '@src/util/type';
import { isTableCellInEdit } from '@src/component/form/form-builder-table/util';
import { randomString } from '@src/util/lang/string';

const TableColumnDefaultWidth = '180px';
const TableColumnDefaultWidthMap: Record<string, any> = {
  // 地址
  [FieldTypeMappingEnum.Address]: '400px',
  // 附件
  [FieldTypeMappingEnum.Attachment]: '260px',
  // 多行文本
  [FieldTypeMappingEnum.Textarea]: '220px',
  // 邮箱
  [FieldTypeMappingEnum.Email]: '260px',
};

/** 
 * @description 表单构建器表格列组件 - 查看模式
*/
const FormBuilderTableColumnView = defineComponent({
  name: ComponentNameEnum.FormBuilderTableColumnView,
  props: {
    column: {
      type: Object as PropType<Column>,
      required: true,
      default: () => ({}),
    },
    row: {
      type: Object as PropType<Record<string, any>>,
      required: true,
      default: () => ({}),
    },
  },
  computed: {
    formType(): string {
      return this.column.formType || '';
    },
    fieldName(): string {
      return this.column.field || this.column.fieldName || '';
    },
    fieldValue(): unknown | string {
      return this.row[this.fieldName] || '';
    },
    fields(): Column[] {
      return [this.column] as Column[];
    },
    isRequired(): boolean {
      return (this.column as Field)?.isNull == 0;
    },
    scopedSlots(): Record<string, any> {
      return this.renderScopeSlots()
    }
  },
  methods: {
    renderScopeSlots() {
      return {
        empty: this.renderScopeSlotsEmpty,
      }
    },
    renderScopeSlotsEmpty() {
      return (
        <div class="form-builder-table-column-view-empty">
          <span>
          
          {/* start 必填符号 */}
          {this.isRequired && (
            <span class="form-item-required">
              *
            </span>
          )}
          {/* end 必填符号 */}
          
          {/* start 点击编辑 */}
          { this.$t('common.paas.component.form.components.formBuilderTableColumnView.clickEdit') }
          {/* end 点击编辑 */}
          
          </span>
        </div>
      )
    }
  },
  render() {
    // 这里的value这么写是因为相关fe里的form-view跟paas里不一致，不是系统字段都是取attribute里，不想改form-view所以兼容
    return (
      <div class={ComponentNameEnum.FormBuilderTableColumnView}>
        <form-view
          fields={this.fields}
          value={{ attribute: this.row, ...this.row}}
          scopedSlots={this.scopedSlots}
        >
        </form-view>
      </div>
    )
  }
})

/** 
 * @description 表单构建器表格列组件 - 编辑模式
*/
const FormBuilderTableColumnFormItem = defineComponent({
  name: ComponentNameEnum.FormBuilderTableColumnFormItem,
  props: {
    column: {
      type: Object as PropType<Column>,
      required: true,
      default: () => ({}),
    },
    row: {
      type: Object as PropType<Record<string, any>>,
      required: true,
      default: () => ({}),
    },
  },
  data() {
    return {
      componentKey: randomString()
    }
  },
  computed: {
    /** 
     * @description 表单类型
    */
    formType(): string {
      return this.column.formType || '';
    },
    /** 
     * @description 字段名
    */
    fieldName(): string {
      return this.column.field || this.column.fieldName || '';
    },
    /** 
     * @description 字段值
    */
    fieldValue(): unknown | string {
      return this.row[this.fieldName] || '';
    },
    /** 
     * @description 字段列表
    */
    fields(): Field[] {
      return [this.column] as Field[];
    },
    /** 
     * @description 是否为附件类型
    */
    isAttachmentField(): boolean {
      return this.formType === FieldTypeMappingEnum.Attachment;
    }
  },
  methods: {
    /** 
     * @description 表单更新事件
    */
    onFormUpdateHandler(event: { newValue: unknown, field: Field }) {
      
      const newValue = event?.newValue;
      const field = event?.field || {};
      const fieldName = field?.fieldName || '';
      
      if (isFalsy(fieldName)) {
        return;
      }
      console.log('update', this.row, fieldName, newValue)
      
      this.$set(this.row, fieldName, newValue);
      
    }
  },
  render() {
    return (
      <div class={ComponentNameEnum.FormBuilderTableColumnFormItem}>
        <form-builder
          key={this.componentKey}
          fields={this.fields}
          value={this.row}
          onUpdate={this.onFormUpdateHandler}
        >
        </form-builder>
      </div>
    )
  }
})

const FormBuilderTableColumnsView = defineComponent({
  name: ComponentNameEnum.FormBuilderTableColumnsView,
  props: {
    columns: {
      type: Array as PropType<Column[]>,
      default: () => [],
      required: true,
    },
    data: {
      type: Array as PropType<Record<string, any>[]>,
      default: () => [],
      required: true,
    },
  },
  methods: {
    getColumnKey(column: Column): string {
      return (column?.field as string || '') + randomString();
    },
    /** 
     * @description 获取列最小宽度
     * @param column 列
    */
    getColumnMinWidth(column: Column): string {
      const formType = column?.formType || '';
      return TableColumnDefaultWidthMap[formType] || TableColumnDefaultWidth;
    },
    /** 
     * @description 渲染表格列 - 默认查看模式
    */
    renderColumn(column: Column, row: Record<string, any>) {
      
      // 是否处于编辑模式
      const isEdit = isTableCellInEdit(row, column);
      
      if (isEdit) {
        return this.renderColumnEdit(column, row);
      }
      
      return this.renderColumnView(column, row);
    },
    /** 
     * @description 渲染表格列 - 查看模式(默认)
    */
    renderColumnView(column: Column, row: Record<string, any>) {
      return (
        <FormBuilderTableColumnView
          column={column}
          row={row}
        >
        </FormBuilderTableColumnView>
      )
      
    },
    /** 
     * @description 渲染表格列 - 编辑模式
    */
    renderColumnEdit(column: Column, row: Record<string, any>) {
      return (
        <FormBuilderTableColumnFormItem
          column={column}
          row={row}
        >
        </FormBuilderTableColumnFormItem>
      )
    }
  },
  render() {
    return (
      <fragment class={ComponentNameEnum.FormBuilderTableColumnsView}>
        {this.columns.map(column => {
          return (
            <el-table-column
              show-overflow-tooltip
              field={column.field}
              title={column.label}
              key={this.getColumnKey(column)}
              column-key={this.getColumnKey(column)}
              label={column.label}
              prop={column.field}
              width={column.width}
              min-width={column.minWidth || this.getColumnMinWidth(column)}
              edit-render={{}}
              scopedSlots={{
                default: (scope: { row: Record<string, any> }) => {
                  const row = scope?.row || {};
                  return this.renderColumn(column, row);
                },
                edit: (scope: { row: Record<string, any> }) => {
                  const row = scope?.row || {};
                  return this.renderColumnEdit(column, row);
                }
              }}
            >
            </el-table-column>
          )
        })}
      </fragment>
    )
  }
})

export {
  FormBuilderTableColumnView,
  FormBuilderTableColumnsView
}
